import {
  Modal,
  TouchableOpacity,
  StyleSheet,
  View,
  Image,
  Text,
  Dimensions,
} from 'react-native';
import React, {
  forwardRef,
  useCallback,
  useEffect,
  useImperativeHandle,
  useState,
} from 'react';

import icon_arrow from '../../../assets/icon_arrow.png';
import icon_delete from '../../../assets/icon_delete.png';
import {save} from '../../../utils/Storage';
const {width: SCREEN_WIDTH} = Dimensions.get('window');

export interface CategoryModalRef {
  show: () => void;
  hide: () => void;
}
type Props = {
  AllCategoryList: Category[];
};
export default forwardRef((props: Props, ref) => {
  const {AllCategoryList} = props;
  const [myList, setMyList] = useState<Category[]>([]);
  const [otherList, setOtherList] = useState<Category[]>([]);
  const [visible, setVisible] = useState<boolean>(false);
  const [edit, setEdit] = useState<boolean>(false);
  useEffect(() => {
    setMyList(AllCategoryList.filter(item => item.isAdd === true));
    setOtherList(AllCategoryList.filter(item => item.isAdd === false));
  }, [AllCategoryList]);
  const show = () => {
    setVisible(true);
  };
  const hide = () => {
    setVisible(false);
  };
  useImperativeHandle(ref, () => {
    return {show, hide};
  });
  const onItemPress = useCallback(
    (item: Category, index: number) => {
      if (!edit || item.default) {
        return;
      }
      const newItem = {...item, isAdd: false};
      const newMyList = myList.filter(i => i.name !== item.name);
      const newOtherList = [...otherList, newItem];
      setMyList(newMyList);
      setOtherList(newOtherList);
    },
    [edit, myList, otherList],
  );
  const onOtherItemPress = useCallback(
    (item: Category, index: number) => {
      if (!edit) {
        return;
      }
      const newItem = {...item, isAdd: true};
      const newMyList = [...myList, newItem];
      const newOtherList = otherList.filter(i => i.name !== item.name);
      setMyList(newMyList);
      setOtherList(newOtherList);
    },
    [edit, myList, otherList],
  );
  const renderMyList = () => {
    return (
      <>
        <View style={styles.row}>
          <Text style={styles.titleTxt}>我的频道</Text>
          <Text style={styles.subTitleTxt}>点击进入频道</Text>
          <TouchableOpacity
            style={styles.editButton}
            onPress={() => {
              setEdit(currentEdit => {
                if (currentEdit) {
                  //点击完成编辑时候保存当前列表
                  save(
                    'categoryList',
                    JSON.stringify([...myList, ...otherList]),
                  );
                  return false;
                } else {
                  return true;
                }
              });
            }}>
            <Text style={styles.editTxt}>{edit ? '完成编辑' : '进入编辑'}</Text>
          </TouchableOpacity>
          <TouchableOpacity style={styles.closeButton} onPress={hide}>
            <Image style={styles.closeImg} source={icon_arrow} />
          </TouchableOpacity>
        </View>
        <View style={styles.myListContainer}>
          {myList.map((item, index) => {
            return (
              <TouchableOpacity
                style={
                  item.default ? styles.myListItemDefault : styles.myListItem
                }
                key={`${item.name}`}
                onPress={() => onItemPress(item, index)}>
                <Text style={styles.myListItemTxt}>{item.name}</Text>
                {edit && !item.default && (
                  <Image
                    style={styles.myListItemCloseIcon}
                    source={icon_delete}
                  />
                )}
              </TouchableOpacity>
            );
          })}
        </View>
      </>
    );
  };
  const renderOtherList = () => {
    return (
      <>
        <View style={[styles.row, {marginTop: 30}]}>
          <Text style={styles.titleTxt}>推荐频道</Text>
          <Text style={styles.subTitleTxt}>点击添加频道</Text>
        </View>
        <View style={styles.myListContainer}>
          {otherList.map((item, index) => {
            return (
              <TouchableOpacity
                style={styles.myListItem}
                key={`${item.name}`}
                onPress={() => {
                  onOtherItemPress(item, index);
                }}>
                <Text style={styles.myListItemTxt}>+{item.name}</Text>
              </TouchableOpacity>
            );
          })}
        </View>
      </>
    );
  };
  return (
    <Modal transparent={true} visible={visible}>
      <View style={styles.root}>
        <View style={styles.content}>
          {renderMyList()}
          {renderOtherList()}
        </View>
      </View>
    </Modal>
  );
});

const styles = StyleSheet.create({
  root: {
    width: '100%',
    height: '100%',
    backgroundColor: 'transparent',
  },
  content: {
    width: '100%',
    height: '80%',
    backgroundColor: 'white',
    marginTop: 50,
  },
  row: {
    width: '100%',
    flexDirection: 'row',
    alignItems: 'center',
  },
  titleTxt: {
    fontSize: 16,
    color: '#333',
    fontWeight: 'bold',
    marginLeft: 16,
  },
  subTitleTxt: {
    fontSize: 13,
    color: '#999',
    marginLeft: 12,
    flex: 1,
  },
  editButton: {
    paddingHorizontal: 10,
    height: 28,
    backgroundColor: '#EEE',
    borderRadius: 14,
    justifyContent: 'center',
    alignItems: 'center',
  },
  editTxt: {
    fontSize: 13,
    color: '#3050ff',
  },
  closeButton: {
    padding: 16,
  },
  closeImg: {
    width: 16,
    height: 16,
    resizeMode: 'contain',
    transform: [{rotate: '90deg'}],
  },
  myListContainer: {width: '100%', flexDirection: 'row', flexWrap: 'wrap'},
  myListItemDefault: {
    width: (SCREEN_WIDTH - 16 * 5) >> 2,
    height: 32,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#eee',
    borderWidth: 1,
    marginLeft: 16,
    marginTop: 12,
    borderColor: '#eee',
    borderRadius: 6,
  },
  myListItem: {
    width: (SCREEN_WIDTH - 16 * 5) >> 2,
    height: 32,
    justifyContent: 'center',
    alignItems: 'center',
    // backgroundColor: 'red',
    borderWidth: 1,
    marginLeft: 16,
    marginTop: 12,
    borderColor: '#eee',
    borderRadius: 6,
  },
  myListItemTxt: {
    fontSize: 16,
    color: '#666',
  },
  myListItemCloseIcon: {
    position: 'absolute',
    width: 16,
    height: 16,
    top: -8,
    right: -8,
  },
});
